﻿
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;

using System.Text;


using System.Web;
using System.Web.UI.WebControls;
using System.Globalization;

using System.Diagnostics;
using System.Diagnostics.Eventing;


namespace ProtocolWorkflows.OutgoingTasksForms
{
    public partial class Task1Form : WebPartPage
    {

        EventLog LogToSystem = new EventLog();



        protected void Page_Load(object sender, EventArgs e)
        {





            AttachButtonsActions();


            if (!IsPostBack)
            {

                LocalizeForm();

                LoadItemProperties();

                ShowControls();
        }

        }


        void AttachButtonsActions()
        {

            btnSaveAsDraft.Click += new EventHandler(btnSaveAsDraft_Click);
            btnApprove.Click += new EventHandler(btnApprove_Click);

            btnReject.Click += new EventHandler(btnReject_Click);

            btnCancel.Click += new EventHandler(btnCancel_Click);

            //btnAccept.Click += new EventHandler(btnAccept_Click);
            btnReturn.Click += new EventHandler(btnReturn_Click);

            btnReassign.Click += new EventHandler(btnReassign_Click);


            btnSend.Click += new EventHandler(btnSend_Click);


        }

        protected void UpdateRequestComments( string Comments)
        {

            if (Comments.Length > 0)
            {


                SPListItem taskItem = SPContext.Current.ListItem;

                string targetListId = taskItem["TargetListId"].ToString();
                string targetListItemId = taskItem["TargetListItemId"].ToString();


                SPList targetList = SPContext.Current.Web.Lists[new Guid(targetListId)];

                SPListItem request = targetList.GetItemById(int.Parse(targetListItemId));




                string approvalComments = "";

                try
                {


                    
                    if (request[request.ParentList.Fields.GetFieldByInternalName("ApprovalComments").Id] != null)
                    {
                        approvalComments = (string)request[request.ParentList.Fields.GetFieldByInternalName("ApprovalComments").Id];
                    }

                }
                catch (Exception codeException)
                {
                    WriteError(codeException);
                }


                StringBuilder CommentBuilder = new StringBuilder();
                CommentBuilder.Append(string.Format("{0} {1} :", DateTime.Now.ToString(), SPContext.Current.Web.CurrentUser.Name));
                CommentBuilder.Append(Environment.NewLine);
                CommentBuilder.Append(Comments);
                CommentBuilder.Append(Environment.NewLine);
                CommentBuilder.Append(Environment.NewLine);
                CommentBuilder.Append(approvalComments);

                //request[ColumnName] = CommentBuilder.ToString();

                request[request.ParentList.Fields.GetFieldByInternalName("ApprovalComments").Id] = CommentBuilder.ToString();
                request.SystemUpdate();


            }

        }


        void ShowControls()
        {
            SPListItem item = SPContext.Current.ListItem;

            string taskStage = "";
            string linkURL = "";

            if (item["TaskStage"] != null)
            {
                taskStage = item["TaskStage"].ToString();
            }


            if (item["LinkToItem"] != null)
            {
                linkURL = item["LinkToItem"].ToString();
            }
            linkDocument.NavigateUrl = linkURL;


            hiddenStage.Value = taskStage;


            btnApprove.Visible = false;
            btnSaveAsDraft.Visible = false;


            #region Hide all controls- and show those for specific stage in workflow
            //btnAccept.Visible = false;
            btnReturn.Visible = false;
            btnReassign.Visible = false;
            btnSend.Visible = false;


     
            panelReassign.Visible = false;

            #endregion


         
            try
            {

                // If closed - then dont enable any buttons
                if ( decimal.Parse(item[SPBuiltInFieldId.PercentComplete].ToString()) == 1)
                {
                    return;
                }

            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }
           

          
            btnReturn.Visible = true;
            btnApprove.Visible = true;

            btnReassign.Visible = false;



        }




        void LocalizeForm()
        {

            labelComments.Text = Resource1.FormCaption_Comments;

            linkDocument.Text = Resource1.FormCaption_Link;
            labelTitle.Text = Resource1.FormCaption_Title;
            //labelDescription.Text = Resource1.FormCaption_Instructions;
    
            labelForward.Text = Resource1.FormCaption_ReassignTask;


            //btnAccept.Text = Resource1.FormCaption_Accept;


            btnReject.Text = Resource1.FormCaption_Reject;
            btnApprove.Text = Resource1.FormCaption_Approve;
            btnReturn.Text = Resource1.FormCaption_Return;
            btnReassign.Text = Resource1.FormCaption_Reassign;
            btnSend.Text = Resource1.FormCaption_Send;
            btnSaveAsDraft.Text = Resource1.FormCaption_Save;
            btnCancel.Text = Resource1.FormCaption_Close;

            labelApprovalComments.Text = Resource1.FormCaption_ApprovalComments;


            labelSubject.Text = Resource1.FormCaption_Subject;
            labelCategory.Text = Resource1.FormCaption_Category;
            labelSubCategory.Text = Resource1.FormCaption_SubCategory;


            labelDocumentType.Text = Resource1.FormCaption_DeliverMethod;
            labelRecipient.Text = Resource1.FormCaption_Recipient;



        }



        void LoadItemProperties()
        {


            SPListItem taskItem = SPContext.Current.ListItem;

            string targetListId = taskItem["TargetListId"].ToString();
            string targetListItemId = taskItem["TargetListItemId"].ToString();


            SPList targetList = SPContext.Current.Web.Lists[new Guid(targetListId)];

            SPListItem targetListItem = targetList.GetItemById(int.Parse(targetListItemId));

            
            try
            {

                labelCategoryValue.Text = GetLookupPropertyValue(targetListItem, "DocumentCategory" );

            }
            catch { ;}


            try
            {
                labelSubCategoryValue.Text = GetLookupPropertyValue(targetListItem, "DocumentSubCategory" );

            }
            catch { ;}


            try
            {

                if (targetListItem[targetListItem.ParentList.Fields.GetFieldByInternalName("DocumentSubject").Id] != null)
                {
                    labelSubjectValue.Text = (string)targetListItem[targetListItem.ParentList.Fields.GetFieldByInternalName("DocumentSubject").Id];

                }
            }
            catch { ;}


            try
            {

                if (targetListItem[targetListItem.ParentList.Fields.GetFieldByInternalName("ApprovalComments").Id] != null)
                {

                    string apprComments = (string)targetListItem[targetListItem.ParentList.Fields.GetFieldByInternalName("ApprovalComments").Id];



                    apprComments = CRLFtoBR(apprComments );


                    labelApprovalCommentsValue.Text = apprComments;

                }
            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }



            try
            {

                labelDocumentTypeValue.Text = GetLookupPropertyValue(targetListItem, "DocumentType");

            }
            catch { ;}


            try
            {

                if (targetListItem[targetListItem.ParentList.Fields.GetFieldByInternalName("DocumentRecipient").Id] != null)
                {

                    labelRecipientValue.Text =targetListItem[targetListItem.ParentList.Fields.GetFieldByInternalName("DocumentRecipient").Id].ToString() ;
                    labelRecipientValue.Text = labelRecipientValue.Text.Substring(labelRecipientValue.Text.IndexOf("#") + 1);

                }

                
            }
            catch { ;}
    

        }


        private  string CRLFtoBR(string text)
        {
            return text.Replace(Environment.NewLine, "<br />");
        } 


       
        


        protected void PopulateLookupListNoCache(DropDownList listControl, string listName)
        {


            SPList SourceList = SPContext.Current.Web.GetList(string.Format("{0}/Lists/{1}", SPContext.Current.Web.ServerRelativeUrl, listName));

            SPQuery ListQuery = new SPQuery();

            //ListQuery.Query = "<OrderBy><FieldRef name=\"Title\" /></OrderBy>";

            SPListItemCollection SourceListItems = SourceList.GetItems(ListQuery);

            for (int i = 0; i < SourceListItems.Count; i++)
            {
                SPListItem SourceListItem = SourceListItems[i];

                ListItem newItem = new ListItem(SourceListItem.Title, SourceListItem.ID.ToString());

                listControl.Items.Add(newItem);
            }


            if (listControl.Items.Count>0)
             listControl.SelectedIndex = 0;


        }


      
        void CloseTask(string outcome)
        {

            SPListItem item = SPContext.Current.ListItem;

            item[SPBuiltInFieldId.TaskStatus] = Resource1.Status_Complete;
            item["TaskOutcome"] = outcome;

            try
            {
                item[item.ParentList.Fields.GetFieldByInternalName("Outcome").Id] = outcome;
            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }


            item[SPBuiltInFieldId.PercentComplete] = 1;

            

            SaveButton.SaveItem(SPContext.Current, false, "");

            if (!string.IsNullOrEmpty(txtComments.Text))
            {
                UpdateRequestComments(txtComments.Text);
            }


            CloseForm();
        }

        void btnAccept_Click(object sender, EventArgs e)
        {

            SPListItem item = SPContext.Current.ListItem;

            item[SPBuiltInFieldId.TaskStatus] = Resource1.Status_InProgress;

            item[SPBuiltInFieldId.AssignedTo] = SPContext.Current.Web.CurrentUser;


            item["TaskStage"] = "accepted";
            item[SPBuiltInFieldId.StartDate] = DateTime.Now;

            SaveButton.SaveItem(SPContext.Current, false, "");


            if (!string.IsNullOrEmpty(txtComments.Text))
            {
                UpdateRequestComments(txtComments.Text);
            }

            CloseForm();
        }

        void btnReturn_Click(object sender, EventArgs e)
        {
            CloseTask(Resource1.Status_Returned);
        }

        void btnReassign_Click(object sender, EventArgs e)
        {

            panelReassign.Visible = true;

            btnReturn.Visible = false;
            btnApprove.Visible = false;
            btnReassign.Visible = false;
            btnSend.Visible = true;

        }


        void btnSend_Click(object sender, EventArgs e)
        {


     
            SPFieldUserValue newOwner = GetUserListForPeopleField(peopleForward.CommaSeparatedAccounts);


            SPListItem item = SPContext.Current.ListItem;
            item[SPBuiltInFieldId.AssignedTo] = newOwner;


            SaveButton.SaveItem(SPContext.Current, false, "");


            if (!string.IsNullOrEmpty(txtComments.Text))
            {
                UpdateRequestComments(txtComments.Text);
            }

            CloseForm();
           
        }



        private string GetLookupPropertyValue(SPListItem item, string fieldName)
        {
            string value = "";

            try
            {




                if (item[item.ParentList.Fields.GetFieldByInternalName(fieldName).Id] != null)
                {
                    string lookupFieldValue = (string)item[item.ParentList.Fields.GetFieldByInternalName(fieldName).Id];

                    if (lookupFieldValue.Length > 0)
                    {
                        value = lookupFieldValue.Substring(lookupFieldValue.IndexOf("#") + 1);
                    }
                }
            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }
            return value;
        }



        private SPFieldUserValue GetUserListForPeopleField(string userNamesList)
        {


            SPFieldUserValue userValue = null;

            //SPFieldUserValueCollection userList = new SPFieldUserValueCollection();


            if (!string.IsNullOrEmpty(userNamesList))
            {

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    SPSite site = new SPSite(Microsoft.SharePoint.SPContext.Current.Web.Url);
                    SPWeb web = site.OpenWeb();

                    web.AllowUnsafeUpdates = true;

                    string[] split = userNamesList.Split(new Char[] { ',', ';' });

                    foreach (string userName in split)
                    {

                        try
                        {
                            SPUser user = web.SiteUsers[userName];

                            userValue = new SPFieldUserValue(web, user.ID, user.Name);

                            break;
                            //userList.Add(userValue);

                        }
                        catch (Exception codeException)
                        {
                            WriteError(codeException);
                        }
                    }

                    web.Dispose();
                    site.Close();

                });


            }

            //return userList;
            return userValue;

        }


        void btnCancel_Click(object sender, EventArgs e)
        {
            CloseForm();
        }

        private void CloseForm()
        {
            if( ( SPContext.Current != null ) && SPContext.Current.IsPopUI )
            {
                this.Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                this.Context.Response.Flush();
                this.Context.Response.End();
            }
            else
            {
                string str = this.Page.Request.QueryString["Source"];
                if( ( str != null ) && ( str.Length > 0 ) )
                {
                    SPUtility.Redirect(string.Empty, SPRedirectFlags.UseSource, this.Context);
                }
            }
        }




        void btnApprove_Click(object sender, EventArgs e)
        {



            SPListItem item = SPContext.Current.ListItem;
            item[SPBuiltInFieldId.TaskStatus] = Resource1.Status_Complete;


            item["TaskOutcome"] = Resource1.Status_Approved;

            item[SPBuiltInFieldId.PercentComplete] = 1;


            SaveButton.SaveItem(SPContext.Current, false, "");


            if (!string.IsNullOrEmpty(txtComments.Text))
            {
                UpdateRequestComments(txtComments.Text);
            }

            CloseForm();
        }

        void btnReject_Click(object sender, EventArgs e)
        {

            SPListItem item = SPContext.Current.ListItem;
            item[SPBuiltInFieldId.TaskStatus] = Resource1.Status_Complete;


            item["TaskOutcome"] = Resource1.Status_Rejected;

            item[SPBuiltInFieldId.PercentComplete] = 1;


            SaveButton.SaveItem(SPContext.Current, false, "");


            if (!string.IsNullOrEmpty(txtComments.Text))
            {
                UpdateRequestComments(txtComments.Text);
            }

            CloseForm();
        }


  
        void btnSaveAsDraft_Click(object sender, EventArgs e)
        {
            SaveButton.SaveItem(SPContext.Current, false, "");

            CloseForm();
        }


        private void WriteError(Exception ex)
        {
            LogToSystem.Source = "SharePoint 2010 Protocols Library";
            LogToSystem.WriteEntry(ex.Message + " : " + ex.StackTrace, EventLogEntryType.Error);

        }
    
    }
}
